package com.aqie.meet.ui.chat;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aqie.libcommon.app.BaseApplication;
import com.aqie.libcommon.app.PresenterFragment;
import com.aqie.libcommon.widget.PortraitView;
import com.aqie.libcommon.widget.adapter.TextWatcherAdapter;
import com.aqie.libcommon.widget.recycle.RecyclerAdapter;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.db.Message;
import com.aqie.libfactory.model.db.User;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.libfactory.persistence.Account;
import com.aqie.libfactory.presenter.message.ChatContract;
import com.aqie.meet.R;
import com.aqie.meet.ui.login.AccountActivity;
import com.aqie.meet.ui.my.MaterialSettingActivity;
import com.bumptech.glide.Glide;

import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static org.litepal.Operator.getHandler;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public abstract class ChatFragment<InitModel>
        extends PresenterFragment<ChatContract.Presenter>
        implements ChatContract.View<InitModel> {

    // 接收者id
    protected String mReceiverId;
    protected String mReceiverUsername;
    protected boolean canTalk;

    private Adapter mAdapter;

    @BindView(R.id.chat_recycler)
    RecyclerView mRecycleView;

    @BindView(R.id.edit_content)
    EditText mContent;

    @BindView(R.id.btn_submit)
    View mSubmit;

    @BindView(R.id.chat_content)
    CoordinatorLayout mChatContent;

    /**
     * 初始化参数接收 接收者id
     *
     * @param bundle
     */
    @Override
    protected void initArgs(Bundle bundle) {
        super.initArgs(bundle);
        mReceiverId = bundle.getString(MessageActivity.KEY_RECEIVER_ID);
        mReceiverUsername = bundle.getString(MessageActivity.USERNAME);
        canTalk = bundle.getBoolean(MessageActivity.KEY_CAN_TALK);

    }

    @OnClick(R.id.action_back)
    void back(){
        if(getActivity()!= null){
            getActivity().finish();
        }
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_chat;
    }


    @Override
    protected void initWidget(View root) {
        super.initWidget(root);

        initEditContent();

        // RecyclerView基本设置
        mRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        // 每次打开滚动到底部
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager)mRecycleView.getLayoutManager();
        //linearLayoutManager.setStackFromEnd(true);
        getHandler().postDelayed(() -> {
        linearLayoutManager.setStackFromEnd(linearLayoutManager.findLastVisibleItemPosition() -
                        linearLayoutManager.findFirstVisibleItemPosition()< mAdapter.getItemCount() -1);
        },50);

        mAdapter = new Adapter();
        mRecycleView.setAdapter(mAdapter);
        // todo 判断data数量 正常情况不需要添加
        if(mAdapter.getItemCount() > 0){
            mAdapter.addFooterView(LayoutInflater.from(getActivity()).inflate(R.layout.cell_chat_footer,null));
            mAdapter.notifyDataSetChanged();
        } else if(!canTalk) {
            mAdapter.addFooterView(LayoutInflater.from(getActivity()).inflate(R.layout.cell_chat_footer,null));
            mAdapter.notifyDataSetChanged();
        }
        // mRecycleView.scrollToPosition(mAdapter.getItemCount() - 1);
        // 添加适配器监听器，进行点击的实现
        mAdapter.setListener(new RecyclerAdapter.AdapterListenerImpl<Message>() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, Message message) {

            }
        });

        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // BaseApplication.showToast("onScrolled");
                Log.e(TAG,dx + " -  " + dy);
                //获取可见item个数
                int lastVisibleItemPosition =
                        linearLayoutManager.findLastVisibleItemPosition();
                //说明是最后一条数据
                if (lastVisibleItemPosition + 1 == mAdapter.getItemCount()) {
                    // BaseApplication.showToast("最后一条数据");
                }
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // BaseApplication.showToast("onScrollStateChanged");
            }
        });

        // 添加滚动
        mChatContent.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom) {
                // BaseApplication.showToast("onLayoutChange");
                Log.e(TAG, "onLayoutChange");
                Log.e(TAG,bottom + " " + oldBottom);
                if(bottom < oldBottom){
                    mRecycleView.scrollToPosition(mAdapter.getItemCount() - 1);
                }
                // mRecycleView.scrollToPosition(mAdapter.getItemCount() - 1);
                /*if (bottom < oldBottom) {
                    //通过RecyclerView的滚动方法将聊天信息滚动到最后一条
                    mRecycleView.scrollToPosition(mAdapter.getItemCount() - 1);
                    // linearLayoutManager.setStackFromEnd(true);
                } else {
                    mRecycleView.scrollToPosition(mAdapter.getItemCount() - 1);
                }*/
            }
        });

    }

    /**
     * important
     * 开始进行初始化操作 调用Presenter#start()
     */
    @Override
    protected void initData() {
        super.initData();
        mPresenter.start();
    }

    // 初始化输入框监听
    private void initEditContent() {
        mContent.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString().trim();
                boolean needSendMsg = !TextUtils.isEmpty(content);
                // 设置状态，改变对应的Icon
                mSubmit.setActivated(needSendMsg);
            }
        });
    }
    private  class Adapter extends RecyclerAdapter<Message> {
        // 重写 RecycleView 点击事件
        private View VIEW_FOOTER;

        // 六种
        @Override
        protected int getItemViewType(int position, Message message) {
            // 我发送的在右边，收到的在左边(发送者id 等于 我的id在右边)
            if(isFooterView(position)){
                return R.layout.cell_chat_footer;
            } else if (message.getStatus() == Message.STATUS_DONE){
                boolean isRight = Objects.equals(message.getSenderId(), Account.getUserId());
                return isRight ? R.layout.cell_chat_text_right : R.layout.cell_chat_text_left;
            } else {
                return R.layout.cell_chat_text_right_error;
            }

        }
        @Override
        public void onAttachedToRecyclerView(RecyclerView recyclerView){
            try{
                if(mRecycleView == null && mRecycleView != recyclerView){
                    mRecycleView =recyclerView;
                }
                ifGridLayoutManager();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        @Override
        protected ViewHolder<Message> onCreateViewHolder(View root, int viewType) {
            switch (viewType) {
                // 左右都是同一个
                case R.layout.cell_chat_footer:
                    return new MyHolder(root);
                default:
                    return new TextHolder(root);
            }
        }
        private View getLayout(int layoutId){
            return LayoutInflater.from(getActivity()).inflate(layoutId,null);
        }

        @Override
        public int getItemCount() {
            int count = super.getItemCount();
            if(VIEW_FOOTER != null){
                count++;
            }
            return count;
        }

        //判断是否是尾部
        private boolean isFooterView(int position){
            return haveFooterView() && position == getItemCount() -1;
        }

        //是否有尾部
        public boolean haveFooterView(){
            return VIEW_FOOTER != null;
        }

        public void addFooterView(View footerView){
            if(haveFooterView()){
                throw new IllegalStateException("haveview has already exists!");
            }else{
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                footerView.setLayoutParams(params);
                VIEW_FOOTER = footerView;
                ifGridLayoutManager();
                notifyItemInserted(getItemCount() - 1);
            }

        }

        private void ifGridLayoutManager(){
            if(mRecycleView == null) return;
            final RecyclerView.LayoutManager layoutManager =mRecycleView.getLayoutManager();
            if(layoutManager instanceof GridLayoutManager){
                final GridLayoutManager.SpanSizeLookup originalSpanSizeLookup =
                        ((GridLayoutManager) layoutManager).getSpanSizeLookup();
                ((GridLayoutManager) layoutManager).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return (isFooterView(position) ?
                                ((GridLayoutManager) layoutManager).getSpanCount() : 1);
                    }
                });

            }
        }
    }


    @Override
    public boolean onBackPressed() {
        return super.onBackPressed();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }



    // Holder的基类
    class BaseHolder extends RecyclerAdapter.ViewHolder<Message> {
        @BindView(R.id.im_portrait)
        PortraitView mPortrait;
        public BaseHolder(View itemView) {
            super(itemView);
        }


        // todo 设置聊天头像
        @Override
        protected void onBind(Message message) {
            User sender = message.getSender();
            // 进行数据加载 (懒加载)
            sender.load();
            mPortrait.setup(Glide.with(ChatFragment.this), sender);

        }

        /**
         * 发送失败 点击头像重新发送
         */
        @OnClick(R.id.im_portrait)
        void onRePushClick() {
            // BaseApplication.showToast("click");
        }
    }

    // 文字的Holder
    class TextHolder extends BaseHolder {
        @BindView(R.id.txt_content)
        TextView mContent;

        public TextHolder(View itemView) {
            super(itemView);
        }

        @Override
        protected void onBind(Message message) {
            super.onBind(message);

            Spannable spannable = new SpannableString(message.getMsg());

            // 把内容设置到布局上
            mContent.setText(spannable);
        }
    }

    public class MyHolder extends RecyclerAdapter.ViewHolder{
        public LinearLayout layout;
        @Nullable
        @BindView(R.id.chat_add_friend)
        TextView mChatAddFriend;
        public MyHolder(View itemView){
            super(itemView);
        }

        @Override
        protected void onBind(Object o) {

        }

        @OnClick(R.id.chat_add_friend)
        void chatAddFriend(){
            addFriend(mReceiverId);
        }

    }

    @Override
    public void onAdapterDataChanged() {
        // 界面没有占位布局，Recycler是一直显示的，所有不需要做任何事情
    }

    @Override
    public RecyclerAdapter<Message> getRecyclerAdapter() {
        return mAdapter;
    }

    @OnClick(R.id.btn_submit)
    void onSubmitClick() {
        if (mSubmit.isActivated()) {
            // websocket 发送文本消息
            String content = mContent.getText().toString();
            mContent.setText("");
            // 改为 presenter 发送
            mPresenter.pushText(content, canTalk);

        } else {

        }
    }

    /**
     * 跳转好友资料设置
     */
    @OnClick(R.id.chat_set)
    void chatSet(){
        Intent intent = new Intent(getActivity(), MaterialSettingActivity.class);
        intent.putExtra("talentsId", mReceiverId);
        startActivity(intent);
    }
    private void addFriend(String friendId) {
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.friendRequestSend(friendId,null,null);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {
                RspModel<Boolean> body = response.body();

                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }
                if(body !=null && body.success()){
                    BaseApplication.showToast("发送成功");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {

            }
        });
    }


}
